<template>
	<view>
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">承载记忆</block>
			
			<u-button :class="{'noCick':!canClick}" type="success" size='mini' slot="right" style="position: absolute;right: 20rpx;"  @tap="btnAClick">发表</u-button>
			
		</cu-custom>
		<u-tabs :list="[{name:'图文'},{name:'视频'}]" :is-scroll="false" :current="current" @change="changeType"></u-tabs>
		<form>
			<view class="cu-form-group ">
				<view class="title">标题</view>
				<input placeholder="标题" name="input" v-model="title" style="text-align: right;"></input>
			</view>
			<view class="cu-form-group " v-if="current==0">
				<textarea maxlength="-1" :disabled="modalName!=null" @input="textareaAInput" placeholder="这一刻的想法~"></textarea>
			</view>
			<view class="cu-bar bg-white margin-top">
				<view class="action">
					{{current==0?'图片上传':'视频上传'}}
				</view>
				<view class="action" v-if="current==0">
					{{list.length}}/50
				</view>
				<view class="action" v-else>
					<u-icon label='添加视频' name="plus-circle" color="#000" size="40" @click="uploadVideo" v-if="!theVideo"></u-icon>
					<u-icon label='移除视频' name="backspace" color="#000" size="40" @click="deleteVideo" v-else></u-icon>
				</view>
			</view>
			<view class="" style="background: #fff;" v-show="current==0">
				<shmily-drag-image ref="dragImage" :list.sync="list" :custom="true" @addImage="addImage"></shmily-drag-image>
			</view>
			<u-line-progress v-if="current==1&&duration" :striped="true" :percent="percentCompleted" :striped-active="true"></u-line-progress>
			<view class="videoBox" v-if="current==1&&theVideo">
				
			       <video id="myVideo"    
						  :src="theVideo"
						  :duration='duration'
						  :poster="theVideo+ '?x-oss-process=video/snapshot,t_0,f_jpg'"
			              style="width: 100%;"
						  enable-danmu danmu-btn controls>
					</video>
			</view>
			
			<view class="cu-form-group margin-top">
				<view class="title">分类</view>
				<picker @change="PickerChange" :value="index" :range="picker">
					<view class="picker">
						{{index>-1?picker[index]:'选择记忆类型'}}
					</view>
				</picker>
			</view>
			
			<view class="cu-form-group">
				<view class="title" >打卡定位</view>
				<view class="" @click="getLocal">
					{{addressStr}}<text class="lg text-gray cuIcon-location"></text>
				</view>
				
				
			</view>
			<view class="cu-form-group">
				<view class="title">日期选择</view>
				<picker mode="date" :value="date" start="1990-09-01" end="2050-09-01" @change="DateChange" :disabled="dateFlg">
					<view class="picker">
						{{date}}
					</view>
				</picker>
			</view>
			
			<view class="cu-form-group">
				<view class="title">允许评论</view>
				<switch @change="SwitchA" :class="switchA?'checked':''" :checked="switchA?true:false"></switch>
			</view>

			
	
			
			
		</form>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		univerifyLogin
	} from '@/common/univerify.js'
	
	import shmilyDragImage from '@/components/shmily-drag-image/shmily-drag-image.vue'
	export default {
		computed: {...mapState(['forcedLogin', 'hasLogin', 'userName']),
		},
		components:{
		  shmilyDragImage
		},
		data() {
			return {
				index: 0,
				picker: ['过往', '当下'],
				dateFlg:false,
				date: '选择记忆时间',
				switchA: false,
				
				modalName: null,
				textareaAValue: '',
				title:'',
				list:[],
				canClick:true,
				current:0,
				theVideo:'',
				duration:0,
				percentCompleted:0,
				loaclAddress:'',
				addressStr:''
				
			};
		},
		onLoad(options) {
			this.current=options.current
		},
		
		watch:{
			index(nv,ov){
				if(nv==1){
					this.dateFlg=true
					let year = new Date().getFullYear()
					let mon = new Date().getMonth()+1
					let day = new Date().getDate()
					this.date=year+'-'+mon+'-'+day
				}else{
					this.dateFlg=false
					this.date='选择记忆时间'
				}
			}
		},
		created() {
			
			uni.getLocation({
			    type: 'wgs84',
				geocode:true,
			    success: function (res) {
			  //       console.log('当前位置的经度：' + res.longitude);
			  //       console.log('当前位置的纬度：' + res.latitude);
					// console.log('当前位置：' + JSON.stringify(res));
					uniCloud.callFunction({
						'name':"getLocal",
						data:res
					}).then(res=>{
						// console.log(res)
						
					}).catch(err=>{
						// console.log(err)
					})
			    }
			});
		},
		
		methods: {
			getLocal(){
				let that = this;
				uni.getLocation({
				    type: 'wgs84',
					geocode:true,
				    success: function (res) {
				        console.log('当前位置的经度：' + res.longitude);
				        console.log('当前位置的纬度：' + res.latitude);
						console.log('当前位置：' + JSON.stringify(res));
						that.loaclAddress = res.address
						that.addressStr = res.address.province+'-'+res.address.city+'-'+res.address.district
				    }
				});
			},
			changeType(index) {
				this.current = index;
			},
			deleteVideo(){
				this.theVideo=''
				this.percentCompleted=0
				this.duration=0
			},
			uploadVideo(){
				let that = this;
				uniCloud.chooseAndUploadFile({
				  type: 'video',
				  onChooseFile(res) {
					  console.log('onChooseFile',res)
					  that.duration = res.tempFiles[0].duration
					  return new Promise((resolve,reject)=>{
						  let result={
							  tempFilePaths: []
							  
						  }
						  result.tempFiles=res.tempFiles.map((fileItem, index)=>{
							  result.tempFilePaths.push(fileItem.path)
							  return{
								  path:fileItem.path,
								  cloudPath:'memory'+fileItem.cloudPath,
								  type:fileItem.type
							  }
						  })
						  resolve(result)
						  console.log(result)
						  return result
					  })
					 
				  },
				 onUploadProgress: function(progressEvent) {
				         var percentCompleted = Math.round(
				             (progressEvent.loaded * 100) / progressEvent.total
				         );
						 //console.log(percentCompleted)
						 that.percentCompleted = percentCompleted;
				   },
				}).then(res => {
				  console.log(res)
					this.theVideo = res.tempFiles[0].url
					console.log(this.theVideo)
				}).catch(err=>{
					console.log(err)
				})
			},
			guideToLogin() {
				let that =this;
				uni.showModal({
					title: '未登录',
					content: '您未登录，需要登录后才能继续',
					/**
					 * 如果需要强制登录，不显示取消按钮
					 */
					showCancel: !this.forcedLogin,
					success: (res) => {
						if (res.confirm) {
							that.goToLogin()
						}
					}
				});
			},
			goToLogin(){
				univerifyLogin().catch((err) => {
					console.log(err,'???')
					if (err === false) return;
					/**
					 * 如果需要强制登录，使用reLaunch方式
					 */
					if (this.forcedLogin) {
						uni.reLaunch({
							url: '/pages/login/login'
						});
					} else {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}
				})
			},
			btnAClick() {
				// 此处用法为在js中调用，需要写this.$u.throttle()
				let uniIdToken = uni.getStorageSync('uni_id_token')
				if(!uniIdToken){
					this.guideToLogin()
				}else{
					
					this.$u.throttle(this.publish(),50000)
				}
				
			},
			publish(){
				let options={}
				if(this.current==0){
					options ={
						type:'image',
						title:this.title,
						content:this.textareaAValue,
						imgList:this.list,
						classfy:this.index,
						classfyLabel:this.picker[this.index],
						canComment:this.switchA,
						memoryDate:this.date,
						publish_dateTime:new Date().getTime(),
						publish_date:this.$u.timeFormat(new Date().getTime(), 'yyyy-mm-dd'),
						quanxian:['all'],
						isPublic:1,
						loaclAddress:this.loaclAddress
					}
				}else{
					 options ={
						type:'video',
						title:this.title,
						video:this.theVideo,
						classfy:this.index,
						duration:this.duration,
						classfyLabel:this.picker[this.index],
						canComment:this.switchA,
						memoryDate:this.date,
						publish_dateTime:new Date().getTime(),
						publish_date:this.$u.timeFormat(new Date().getTime(), 'yyyy-mm-dd'),
						quanxian:['all'],
						isPublic:1,
						loaclAddress:this.loaclAddress
					}
				}
				
				if(!options.title){
					uni.showToast({
						title:'请设置标题',
						icon:'none'
					})
					return false
				}
				if(this.current==0&&options.imgList.length==0){
					uni.showToast({
						title:'请至少发布一张图片~',
						icon:'none'
					})
					return false
				}
				if(this.current==1&&options.video==''){
					uni.showToast({
						title:'请上传视频~',
						icon:'none'
					})
					return false
				}
				if(this.index==0&&this.date=='选择记忆时间'){
					uni.showToast({
						title:'过往类型需设置时间',
						icon:'none'
					})
					return false
				}
				let that = this
				that.canClick=false
				uniCloud.callFunction({
					name:'publish-memory',
					data:{
						...options
					},
					success:(res) => {
						
						uni.showToast({
							title:'发布成功'
						})
						
						setTimeout(()=>{
							that.canClick=true
							uni.navigateBack()
						},1000)
					},
					fail(e) {
						that.canClick=true
						console.log(e)
					}
				})
			},
			addImage(){
			  // 打开图片裁剪
			  // ...
			  let that = this;
			  uniCloud.chooseAndUploadFile({
			    type: 'image',
			    onChooseFile(res) {
			      const processAll = []
			      for (let i = 0; i < res.tempFiles.length; i++) {	  
			        processAll.push(that.cropImg(res.tempFiles[i]))	
			      }
			      return Promise.all(processAll).then((fileList) => {
					  console.log(fileList)
			        let result = {
			          tempFilePaths: []
			        }
			        result.tempFiles = fileList.map((fileItem, index) => {
			          result.tempFilePaths.push(fileItem.path)
			          return {
			            path: fileItem.path,
			            cloudPath: 'memory' + Date.now() + index + '.' + fileItem.ext, // 云端路径，这里随便生成了一个
			            fileType: fileItem.fileType
			          }
			        })
					console.log(result)
			        return result
			      })
			    }
			  }).then(res => {
			    console.log(res)
				let imgListObj =res.tempFiles 
				for(let i=0;i<imgListObj.length;i++){
					 that.$refs.dragImage.addImage(imgListObj[i].url)
				}
			  })
			  // 将裁剪后图片地址添加到图片列表
			  // this.$refs.dragImage.addImage('http://static-11ea0c21-6b8f-47f7-b77f-cb0c7ea3f355.bspapp.com/shmily-drag-image/static/4.jpg')
			},
			cropImg(file) {
			  return new Promise((resolve, reject) => {
			    let ext
			    let filePathProcessed = file.path // 处理结果
				console.log(filePathProcessed)
			    // #ifdef H5
			    ext = file.name.split('.').pop()
			    resolve({
			      path: filePathProcessed,
			      ext,
			      fileType: file.fileType
			    })
			    // #endif
			    // #ifndef H5
			    uni.getImageInfo({
			      src: file.path,
			      success(info) {
					  console.log(info)
			        ext = info.type.toLowerCase()
			        resolve({
			          path: filePathProcessed,
			          ext,
			          fileType: file.fileType
			        })
			      },
			      fail(err) {
					  console.log(err)
			        reject(new Error(err.errMsg || '未能获取图片类型'))
			      }
			    })
			    // #endif
			  })
			},
			PickerChange(e) {
				this.index = e.detail.value
			},

			DateChange(e) {
				this.date = e.detail.value
			},
			
			SwitchA(e) {
				this.switchA = e.detail.value
			},
		

			textareaAInput(e) {
				this.textareaAValue = e.detail.value
			},

		}
	}
</script>

<style>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
	.noCick{
		pointer-events: none;
	}
</style>
